/*
 * @Date: 2022-09-27 10:44:37
 * @LastEditTime: 2022-10-29 18:21:44
 * @Description: websocket
 */
import { store } from '@/store';
import socket from '@/utils/socket';
import { defineStore } from 'pinia';
import { useUserStore } from '@/store/modules/user';
import axios from "@/axios";


interface SocketState {
    //消息数组
    // socketList: any[];
    ws: any;

}

export const useSocketStore = defineStore({
    id: 'sockets',
    state: (): SocketState => ({
        // socketList: [],
        ws: undefined
    }),
    getters: {
        getCurrentMenu(): any {
            // return this.currentMenu;
        },
    },
    actions: {
        initSocket() {
            if (!this.ws) {
                this.ws = new socket({
                    // @ts-ignore
                    url: axios.getBaseURL() + '/xtxx/' + useUserStore().getToken,
                    onmessage: (data: any) => {
                        if (data) {
                            this.receiveMsg(data)
                        }
                    }
                })
            }
        },
        close(){
            if (this.ws) {
                this.ws.destroy();
                this.ws = null;
            }
        },
        /**
         * @description: 发送消息
         * @param {any} data
         * @return {*}
         */
        sendMsg(data: any) {
            if (this.ws)
                this.ws.send(data)
        },
        /**
         * @description: 接收消息后的处理
         * @param {any} data
         * @return {*}
         */
        receiveMsg(data: any) {
            // this.socketList.unshift(data);
        }
    },
})

// Need to be used outside the setup
export function useSocketStoreWithOut() {
    return useSocketStore(store);
}
